var vm = require('vm');
var fs = require('fs');
var path = require('path');

var self = null;
module.exports = {
	config: null,
	init(config){
		self = this;
		self.config = config;
	},
	load_module(javascript_path, custom_context){
		let default_exports = {};
		
		let default_context = {
			require: function(name) {
				let full_path = path.resolve(path.dirname(javascript_path), name);  //  转成完整路径
				let paths = self.config.ban_load_package.filter((p) => full_path.includes(p));  //  判断是否在禁止加载包列表中
				if (paths && paths.length > 0) throw `module load [${javascript_path}] fail..ban load path[${paths[0]}]`;  //  抛错
				return require(full_path);  //  加载并返回
			},
			console: console,
			exports: default_exports,
			module: { exports: default_exports },
			
		};
		let context = Object.assign({}, default_context, custom_context);
		vm.runInNewContext(fs.readFileSync(javascript_path), context,{
			filename: javascript_path,
		});
		
		let proxy_context = new Proxy(context, {
			set(target, propKey, value, receiver){
				return Reflect.set(target, propKey, value, receiver);
			},
			get(target, propKey, receiver){
				return Reflect.get(target, propKey, receiver);
			},
			has(target, propKey){
				return Reflect.has(target, propKey);
			},
			ownKeys(target){
				let keys = Reflect.ownKeys(target);
				keys.splice(keys.findIndex((item) => item == "require"), 1);
				return keys;
			}
		});
		return proxy_context;
	}
};